package Q4;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket socket;//成员变量
    public ServerThread(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"请求登录!!");
        //获取输入流
        ObjectInputStream ois=null;
        DataOutputStream dos=null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            User user=(User) ois.readObject();
            System.out.println(socket.getInetAddress().getHostAddress()+"请求登录：用户名"+user.getUserName()+"\t密码"+user.getPassword());
            //3.对用户名和密码进行验证
            String str="";
            if("admin".equals(user.getUserName())&&"123456".equals(user.getPassword())){
                str="登录成功！";
            }else{
                str="登录失败";
            }
            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(str);
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }finally{
            //关闭流
            if(dos!=null){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
